<template>
	<view class="container">
		<u-navbar v-if="type !== 1" title="附近商圈-发帖" :autoBack="true" :fixed="true" :bgColor="'#ffffff'"
			:placeholder="true" :titleStyle="{
        color: '#333',
        fontSize: '16px',
      }"></u-navbar>

		<!-- 发布机会提示 -->
		<view class="publish-tip">
			<!-- 您当前还有
      <view class="num">1</view>
      次发布机会 -->
			{{ newtext }}
		</view>

		<!-- 表单内容 -->
		<view class="form-content">
			<!-- 区域 -->
			<view class="form-item arrow" @click="selectArea">
				<text class="label required">区域</text>
				<input class="input" v-model="form.area" placeholder="区域" placeholder-style="color: #999" disabled />
				<u-icon name="arrow-right" color="#999" size="16"></u-icon>
			</view>
			<u-picker :show="showArea" :columns="columnsArea" @cancel="cancelArea" @confirm="confirmArea"
				keyName="name"></u-picker>

			<!-- 位置 -->
			<view class="form-item" @click="selectLocation">
				<text class="label">位置</text>
				<input class="input" v-model="form.location" placeholder="位置" placeholder-style="color: #999"
					disabled />
				<u-icon name="map" color="#2979ff" size="16"></u-icon>
			</view>

			<!-- 描述 -->
			<view class="form-item textarea">
				<textarea v-model="form.description" placeholder="此处填写房子详情描述，参考格式：房子位置+户型+租金+房子其他详情信息"
					placeholder-style="color: #999"></textarea>
			</view>

			<!-- 图片上传 -->
			<view class="upload-section">
				<view class="upload-title">上传照片</view>
				<view class="upload-tip">最多上传9张图片</view>

				<view class="upload-content">
					<u-upload :fileList="fileList1" @afterRead="afterRead" @delete="deletePic" name="1" multiple
						:maxCount="9">
						<view class="upload-item">
							<u-icon name="photo" size="28" color="#0095f8"></u-icon>
							<text>上传图片</text>
						</view>
					</u-upload>
				</view>
				<view class="upload-content" style="margin-top: 20rpx">
					<u-upload :fileList="fileList2" @afterRead="afterRead2" @delete="deletePic2" name="2" multiple
						v-if="!videoUrl" accept="video" :maxCount="1">
						<view class="upload-item">
							<image :src="video_icon" style="width: 56rpx; margin-bottom: 12rpx" mode="widthFix"></image>
							<text>上传视频</text>
						</view>
					</u-upload>
					<view style="width: 100%">
						<video v-if="videoUrl" :src="videoUrl" controls style="width: 100%; height: 240rpx">
							<u-icon name="trash" size="28" style="position: absolute; right: 20rpx; top: 10rpx"
								v-if="videoUrl" color="#0095f8" @click="deletePic2()"></u-icon>
						</video>
					</view>
				</view>

				<!-- <view class="upload-content">
          <view class="upload-item" @click="uploadImage">
            <u-icon name="photo" size="28" color="#0095f8"></u-icon>
            <text>上传图片</text>
          </view>

          <view class="upload-item" @click="uploadVideo">
            <image
              :src="video_icon"
              style="width: 56rpx; margin-bottom: 12rpx"
              mode="widthFix"></image>
            <text>上传视频</text>
          </view>
          <view style="width: 100%">
            <video
              v-if="videoUrl"
              :src="videoUrl"
              controls
              style="width: 100%; height: 240rpx">
              <u-icon
                name="trash"
                size="28"
                style="position: absolute; right: 20rpx; top: 10rpx"
                v-if="videoUrl"
                color="#0095f8"
                @click="deletePic2()"></u-icon>
            </video>
          </view>
        </view> -->
			</view>

			<!-- 附件上传 -->
			<view class="upload-section">
				<view class="upload-title">上传附件</view>
				<view class="upload-tip">支持rar.zip类型</view>

				<view class="upload-content">
					<uni-file-picker v-model="form.contractFileList" limit="9" file-mediatype="all"
						file-extname="zip,rar" auto-upload="true" @select="selectFlie1"></uni-file-picker>
					<!-- <view class="upload-item" @click="uploadFile">
            <image
              src="@/static/uploadImg/uploadFile.png"
              mode=""
              style="width: 46rpx;height: 46rpx; margin-bottom: 12rpx"></image>
            <text>上传附件</text>
          </view> -->
				</view>
			</view>

			<!-- 标签选择 -->
			<view class="tags-section">
				<view class="tags-list">
					<view class="tag-item" v-for="(tag, index) in tags" :key="index"
						:class="{ active: form.selectedTags.includes(tag) }" @click="toggleTag(tag)">
						{{ tag }}
					</view>
				</view>
				<view class="add-tag" @click="addNewTag">
					<u-icon name="plus" color="#2979ff" size="12"></u-icon>
					<text>新增标签</text>
				</view>
			</view>
			<u-modal :show="tagshow" title="新增标签" confirmText="确认" cancelText="取消" :showCancelButton="true"
				@cancel="tagCancel" @confirm="tagConfirm">
				<view class="slot-content">
					<u--input placeholder="请输入标签" border="surround" v-model="tagvalue"></u--input>
				</view>
			</u-modal>
			<!-- 联系方式 -->
			<view class="section-title">联系方式</view>
			<view class="contact-section">
				<view class="form-item">
					<text class="label">联系人</text>
					<input class="input" v-model="form.contact" placeholder="请填写联系人姓名"
						placeholder-style="color: #999" />
				</view>
			<!-- 	<view class="form-item">
					<text class="label">手机号</text>
					<input class="input" v-model="form.phone" type="number" maxlength="11" placeholder="请填写手机号"
						placeholder-style="color: #999" />
				</view> -->
				<view class="form-item">
					<text class="label">微信名</text>
					<input class="input" v-model="form.wechat" placeholder="请填写微信名" placeholder-style="color: #999" />
				</view>
			</view>
		</view>
		<!-- 提交按钮 -->
		<view class="submit-btn" @click="handleSubmit">确认发布</view>
	</view>
</template>

<script>
	import {
		getHouseTypeList,
		getContractTypeList,
		getTypeList,
		publishshop,
		getTagList,
		getArea2,
		getSendType,
	} from "@/api/gent.js";

	export default {
		props: ["type"],
		data() {
			return {
				video_icon: this.$Config.HTTP_REQUEST_URL + "/img/icon30.png",
				form: {
					area: "",
					location: "",
					description: "",
					images: [],
					videos: [],
					files: [],
					selectedTags: [],
					contact: "",
					phone: "",
					wechat: "",
					contractFileList: [],
				},
				showArea: false,
				columnsArea: [
					[],
				],
				tagshow: false,
				tagvalue: "",
				tags: ["免管理费", "免网费", "交通便利", "公寓", "民房", "民用水电"],
				fileList1: [],
				fileList2: [],
				fileList3: [],
				videoUrl: "",
				iimg: [],
				nameList: [],
				currentId: "",
				newtext: "",
			};
		},
		mounted() {
			this.getArea();
			this.getTagList();
			this.getSendType();
		},
		methods: {
			
			async getSendType() {
				const res = await getSendType();
				if (res.response.statusCode === 200) {
					console.log(res.data.data.text);
					this.newtext = res.data.data.text;
				}
			},
			async getArea() {
				const res = await getArea2({
					cid: 2,
				});
				if (res.response.statusCode === 200) {
					var ar = Object.entries(res.data.data).map(([key, value]) => ({
						name: value,
						id: key,
					}));
					this.columnsArea = [
						[...ar]
					];
				}
			},
			async getTagList() {
				const res = await getTagList();
				if (res.response.statusCode === 200) {
					this.tags = Object.values(res.data.data);
				}
			},
			selectArea() {
				// 选择区域
				this.showArea = true;
			},
			selectLocation() {
				var that = this;
				wx.chooseLocation({
					type: "gcj02",
					success: (res) => {
						console.log(res);
						that.form.location = res.name;
						that.form.latitude = res.latitude;
						that.form.longitude = res.longitude;
					},
				});
			},

			uploadImage() {
				// 上传图片
				uni.chooseImage({
					count: 9,
					success: (res) => {
						this.form.images = [...this.form.images, ...res.tempFilePaths];
					},
				});
			},
			// 上传文件（非图片）
			uploadFlie(path, successUrl, comp = () => {}) {
				uni.showLoading({
					title: "上传中...",
				});
				uni.uploadFile({
					url: this.$Config.HTTP_REQUEST_URL + "/api/common/ossUpload",
					filePath: path,
					fileType: "all",
					name: "file",
					header: {
						token: uni.getStorageSync("userInfo").token,
					},
					success: (res) => {
						if (JSON.parse(res.data).code == 0) {
							return uni.showToast({
								title: JSON.parse(res.data).msg,
								icon: "error", //如果要纯文本，不要icon，将值设为'none'
								duration: 2000, //持续时间为 2秒
							});
						} else {
							successUrl(
								JSON.parse(res.data).code == undefined ?
								"" :
								JSON.parse(res.data).code.fullurl
							);
						}
					},
					fail: () => {},
					complete: (res) => {
						uni.hideLoading();
						comp();
					},
				});
			},
			selectFlie1(e) {
				let imgList = [];
				let proArr = [];
				let nameList = [];
				let taht = this;
				let filestr = null;
				if (this.form.contractFileList == undefined) {
					filestr = "";
				} else {
					if (this.form.contractFileList.length == 0) {
						filestr = "";
					} else {
						if (this.form.contractFileList[0].url) {
							let a = [];
							this.form.contractFileList.forEach((i) => {
								a.push(i.url);
							});
							filestr = a.join();
						} else {
							filestr = this.form.contractFileList.join();
						}
					}
				}
				let namestr =
					this.form.contractFileName == undefined ?
					"" :
					this.form.contractFileName.split(",").join();
				e.tempFilePaths.forEach((item, index) => {
					let p = new Promise((resolve, reject) => {
						taht.uploadFlie(item, (res) => {
							let str = res;
							imgList.push(str);
							resolve();
						});
					});
					proArr.push(p);
				});
				Promise.all(proArr).then((res) => {
					let a = imgList.join() + "," + filestr;
					let c = a.split(",").filter((s) => {
						return (s = s.trim());
					});
					e.tempFiles.forEach((i) => {
						nameList.push(i.name);
					});
					let b = nameList.join() + "," + namestr;
					this.form.contractFileName = b;
					let f = [];
					c.forEach((item, index) => {
						f.push({
							name: this.form.contractFileName.split(",")[index],
							url: item,
						});
					});
					this.form.contractFileList = f;
				});
			},
			// 删除图片
			deletePic(event) {
				this[`fileList${event.name}`].splice(event.index, 1);
			},
			// 新增图片
			async afterRead(event) {
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file);
				let fileListLen = this[`fileList${event.name}`].length;
				lists.map((item) => {
					this[`fileList${event.name}`].push({
						...item,
						status: "uploading",
						message: "上传中",
					});
				});
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url);
					let item = this[`fileList${event.name}`][fileListLen];
					this[`fileList${event.name}`].splice(
						fileListLen,
						1,
						Object.assign(item, {
							status: "success",
							message: "",
							url: result.fullurl,
						})
					);
					fileListLen++;
				}
			}, // 删除视频
			deletePic2() {
				this.fileList2.splice(0, 1);
				this.videoUrl = "";
			},
			// 新增图片
			async afterRead2(event) {
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file);
				let fileListLen = this[`fileList${event.name}`].length;
				lists.map((item) => {
					this[`fileList${event.name}`].push({
						...item,
						status: "uploading",
						message: "上传中",
					});
				});
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise2(lists[i].url);
					this.videoUrl = result.fullurl;
					let item = this[`fileList${event.name}`][fileListLen];
					this[`fileList${event.name}`].splice(
						fileListLen,
						1,
						Object.assign(item, {
							status: "success",
							message: "",
							url: result.fullurl,
						})
					);
					fileListLen++;
				}
			},
			uploadFilePromise2(url) {
				return new Promise((resolve, reject) => {
					const token = uni.getStorageSync("userInfo").token;
					uni.uploadFile({
						url: this.$Config.HTTP_REQUEST_URL + "/api/common/upload",
						fileType: "all",
						name: "file",
						filePath: url,
						header: {
							token: token,
						},
						success: (res) => {
							console.log(res.data, JSON.parse(res.data).data);
							setTimeout(() => {
								resolve(JSON.parse(res.data).data);
							}, 1000);
						},
					});
				});
			},
			uploadFilePromise(url) {
				return new Promise((resolve, reject) => {
					const token = uni.getStorageSync("userInfo").token;
					uni.compressImage({
						src: url,
						quality: 50,
						success: (chooseImageRes) => {
							console.log(chooseImageRes, "1");
							uni.uploadFile({
								url: this.$Config.HTTP_REQUEST_URL + "/api/common/upload",
								fileType: "all",
								name: "file",
								filePath: chooseImageRes.tempFilePath,
								header: {
									token: token,
								},
								success: (res) => {
									setTimeout(() => {
										resolve(JSON.parse(res.data).data);
									}, 1000);
								},
							});
						},
					});
				});
			},

			// deletePic2() {
			//   this.videoUrl = "";
			// },
			uploadVideo() {
				// 上传视频
				var that = this;
				uni.chooseVideo({
					success: (res) => {
						this.form.videos.push(res.tempFilePath);
						const token = uni.getStorageSync("userInfo").token;
						uni.uploadFile({
							url: this.$Config.HTTP_REQUEST_URL + "/api/common/upload",
							fileType: "all",
							name: "file",
							filePath: res.tempFilePath,
							header: {
								token: token,
							},
							success: (res) => {
								// console.log(res.data, JSON.parse(res.data).data);
								that.videoUrl = JSON.parse(res.data).data.fullurl;
							},
						});
					},
				});
			},
			uploadFile() {
				// 上传附件
				uni.uploadFile({
					success: (res) => {
						this.form.files.push(res.tempFilePath);
					},
				});
			},
			cancelArea() {
				this.showArea = false;
			},
			confirmArea(e) {
				this.showArea = false;
				this.form.area = e.value[0].name;
				this.form.area_id = e.value[0].id;
			},
			toggleTag(tag) {
				const index = this.form.selectedTags.indexOf(tag);
				if (index > -1) {
					this.form.selectedTags.splice(index, 1);
				} else {
					this.form.selectedTags.push(tag);
				}
			},
			addNewTag() {
				// 添加新标签
				this.tagshow = true;
			},
			tagCancel() {
				// 添加新标签
				this.tagshow = false;
				this.tagvalue = "";
			},
			tagConfirm() {
				// 添加新标签
				this.tagshow = false;
				if (this.tagvalue != "") {
					this.tags.push(this.tagvalue);
					this.tagvalue = "";
				}
			},
			async handleSubmit() {
				// 提交表单

				if (this.form.area == "") {
					return uni.showToast({
						title: "请选择区域",
						icon: "none",
						duration: 2000,
					});
				}
				var contcatarr = this.fileList1.concat(this.fileList2);
				console.log("提交表单", this.form, this.fileList1, this.fileList2);
				var arr = [],
					file = [];
				contcatarr.forEach((element, index) => {
					arr.push(element.url);
				});
				this.form.contractFileList.forEach((element, index) => {
					file.push(element.url);
				});
				console.log(arr.join(","));
				const res = await publishshop({
					area_id: this.form.area_id,
					name: this.form.contact,
					phone: this.form.phone,
					wx_num: this.form.wechat,
					lng: this.form.longitude,
					lat: this.form.latitude,
					address: this.form.location,
					desc: this.form.description,
					photos: arr.join(","),
					tags: this.form.selectedTags.join(","),
					attachment: file.join(","),
				});
				if (res.response.data.code === 1) {
					uni.showToast({
						title: "发布成功",
						icon: "none",
						duration: 2000,
					});
					setTimeout(() => {
						uni.reLaunch({
							url: "/pages/nearby-shop/nearby-shop",
						});
					}, 1000);

					// Object.keys(this.form).forEach((key) => {
					//   this.form[key] = "";
					// });
					// arr = [];
					// this.fileList1 = [];
					// this.fileList2 = [];
					// this.videoUrl = "";
				}
			},
		},
	};
</script>

<style lang="less" scoped>
	.container {
		min-height: 100vh;
		background-color: #f5f6fa;
		padding-bottom: calc(24rpx + env(safe-area-inset-bottom));
	}

	.publish-tip {
		display: flex;
		padding: 20rpx 24rpx;
		font-size: 24rpx;
		color: #999;

		.num {
			color: #ff0000;
		}
	}

	.form-content {
		padding: 0 24rpx;

		.form-item {
			background: #fff;
			border-radius: 12rpx;
			padding: 24rpx;
			margin-bottom: 24rpx;
			display: flex;
			align-items: center;

			&.arrow {
				padding-right: 24rpx;
			}

			.label {
				font-size: 28rpx;
				color: #333;
				margin-right: 24rpx;

				&.required::before {
					content: "*";
					color: #ff5a5f;
					margin-right: 4rpx;
				}
			}

			.input {
				flex: 1;
				text-align: right;
				font-size: 28rpx;
			}

			.value {
				flex: 1;
				font-size: 28rpx;
				color: #333;

				&.location {
					color: #2979ff;
				}
			}

			&.textarea {
				padding: 24rpx;
				align-items: flex-start;

				textarea {
					width: 100%;
					height: 200rpx;
					font-size: 28rpx;
				}
			}
		}
	}

	.upload-section {
		background: #fff;
		border-radius: 12rpx;
		padding: 24rpx;
		margin-bottom: 24rpx;

		.upload-title {
			font-size: 28rpx;
			color: #333;
			margin-bottom: 16rpx;
		}

		.upload-tip {
			font-size: 24rpx;
			color: #999;
			margin-bottom: 24rpx;
		}

		.upload-content {
			display: flex;
			flex-wrap: wrap;
			gap: 24rpx;

			.upload-item {
				width: 160rpx;
				height: 160rpx;
				background: #f5f6fa;
				border-radius: 8rpx;
				display: flex;
				flex-direction: column;
				align-items: center;
				justify-content: center;

				text {
					font-size: 24rpx;
					color: #999;
					margin-top: 8rpx;
				}
			}
		}
	}

	.tags-section {
		background: #fff;
		border-radius: 12rpx;
		padding: 24rpx;
		margin-bottom: 24rpx;

		.tags-list {
			display: flex;
			flex-wrap: wrap;
			gap: 16rpx;
			margin-bottom: 24rpx;

			.tag-item {
				padding: 12rpx 24rpx;
				font-size: 24rpx;
				color: #666;
				background: #f5f5f5;
				border-radius: 4rpx;

				&.active {
					color: #2979ff;
					background: rgba(41, 121, 255, 0.1);
				}
			}
		}

		.add-tag {
			display: flex;
			align-items: center;
			font-size: 24rpx;
			color: #2979ff;

			text {
				margin-left: 8rpx;
			}
		}
	}

	.section-title {
		font-size: 28rpx;
		color: #333;
		margin-bottom: 24rpx;
	}
	
	.contact-section {
		.form-item {
			background: #fff;
			border-radius: 12rpx;
			padding: 38rpx;
			margin-bottom: 24rpx;
		}
	}
	

	.submit-btn {
		margin: 0 24rpx;
		height: 88rpx;
		line-height: 88rpx;
		text-align: center;
		background: #2979ff;
		border-radius: 44rpx;
		color: #fff;
		font-size: 32rpx;
	}
</style>